import axios from 'axios'
import type { 
  ChatRequest, 
  ChatResponse, 
  ChatLog, 
  ChatStatistics,
  SystemHealth,
  SystemInfo
} from '@/types'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加请求ID
    config.headers['X-Request-ID'] = generateRequestId()
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const message = error.response?.data?.message || error.message || '网络错误'
    return Promise.reject(new Error(message))
  }
)

// 生成请求ID
function generateRequestId(): string {
  return Math.random().toString(36).substring(2, 15)
}

// 聊天相关API
export const chatApi = {
  // 发送聊天消息
  async sendMessage(request: ChatRequest): Promise<ChatResponse> {
    return api.post('/chat', request)
  },

  // 获取聊天历史
  async getChatHistory(sessionId: string): Promise<ChatLog[]> {
    return api.get(`/chat/history/${sessionId}`)
  },

  // 获取最近聊天记录
  async getRecentChats(limit: number = 20): Promise<ChatLog[]> {
    return api.get('/chat/recent', { params: { limit } })
  },

  // 获取聊天统计信息
  async getChatStatistics(): Promise<ChatStatistics> {
    return api.get('/chat/statistics')
  },

  // 清除聊天历史
  async clearChatHistory(sessionId: string): Promise<string> {
    return api.delete(`/chat/history/${sessionId}`)
  },

  // 健康检查
  async healthCheck(): Promise<string> {
    return api.get('/chat/health')
  }
}

// 系统相关API
export const systemApi = {
  // 系统健康检查
  async getSystemHealth(): Promise<SystemHealth> {
    return api.get('/system/health')
  },

  // 获取系统信息
  async getSystemInfo(): Promise<SystemInfo> {
    return api.get('/system/info')
  },

  // 测试数据库连接
  async testDatabaseConnection(): Promise<{ connected: boolean; message: string; timestamp: number }> {
    return api.get('/system/database/test')
  },

  // 测试AI服务连接
  async testAiConnection(): Promise<{ connected: boolean; message: string; timestamp: number }> {
    return api.get('/system/ai/test')
  },

  // 获取表结构
  async getTableSchema(tableName: string): Promise<Array<Record<string, any>>> {
    return api.get(`/system/database/schema/${tableName}`)
  }
}

export default api